<?php
include_once("../../includes/config.inc.php");
check_login();
$suserSession=get_suser();
$customer_id=$suserSession['id'];
$model=D('info_common');
$smarty->assign('cateName','文字回复');

/**
 * 数据保存
 * 一条信息对应info_commmon中一条数据
 * 一条信息可能对应keyword_list中多条数据
 */
if($_REQUEST['a']=='add'){
	if(method_is('post')){
		$data=$_POST;
        $data['num']['customer_id']=$customer_id;
        $data['num']['info_type']='1';
        
        //关键词过滤
        $data['str']['keyword'] = str_replace("，",",",$data['str']['keyword']);
        $keyArray = explode(',',$data['str']['keyword']);
        $keyTable = D('keyword_list');
        foreach($keyArray as $v){
            $kRes=$keyTable->where("customer_id='{$customer_id}' and keyword='{$v}'")->dataArr();
            if($kRes && !$data['num']['id']){
                die("关键词 ".$v." 已存在，请更换");
            }elseif($data['num']['id']){
                $kEditRes=$keyTable->where("info_id!='".$data['num']['id']."' and customer_id='{$customer_id}' and keyword='{$v}'")->dataArr();
                if($kEditRes){
                    die("关键词 ".$v." 已存在，请更换");
                }
            }
        }
        
        $res=$model->add($data);
        //保存keyword_list表
        $info_id = $data['num']['id'] ? $data['num']['id'] : $res;
        $arr=array('customer_id'=>$customer_id,'info_id'=>$info_id,'keyword'=>$data['str']['keyword'],'info_type'=>'text');
        Model_Table::get('KeywordList')->saveForKeywords($arr);
        die('suc');
	}else{
		$id=(int)$_GET['id'];
		if($id){
			$smarty->assign('infoRow',$model->find($id));
		}

        //敏感词
        $row=array();
        $arr = D('wx_sense')->dataArr();
        foreach($arr as $k=>$v){
            if($v['word']) $row[]=$v['word'];
        }
        $senseRow = $row ? json_encode($row) : '';
        $smarty->assign('senseRow',$senseRow);

		$smarty->setTpl('info/templates/text.html')->display();die();
	}
}

//数据删除
if($_REQUEST['a']=='del'){
    $res=$model->del((int)$_POST['id']);
    $model->query("delete from keyword_list where info_id='".(int)$_POST['id']."' and customer_id='{$customer_id}'");
    die('suc');
}

//数据列表
$filter=array();
$filter['where'] = "customer_id='{$customer_id}' and info_type='1' ";
if($_GET['keyword']) $filter['where'].=" and keyword like '%".common_pg('keyword')."%'";
$filter['order'] = "id desc";
$data = $model->paginate($filter,'*',common_pg('p'),10);
$listArr = $data['data'];
$smarty->assign('list',$listArr);
$smarty->assign('page',$model->pager($data['pager']));
$smarty->setTpl('info/templates/text_index.html')->display();